package com.java.comprehensive.arithmetic.leecode.medium;

import cn.hutool.core.util.ArrayUtil;

import java.util.*;

public class LeetCode_15 {
    public static List<List<Integer>> threeSum(int[] nums) {
        quickSort(nums, 0, nums.length - 1);
        Set<List<Integer>> result = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int lNum = nums[l];
                int rNum = nums[r];
                int numSum = temp + lNum + rNum;
                if (numSum > 0) {
                    r--;
                } else if (numSum < 0) {
                    l++;
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(lNum);
                    list.add(rNum);
                    list.add(temp);
                    result.add(list);
                    l++;
                    r--;
                }
            }
        }

        return new ArrayList<>(result);
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};

        List<List<Integer>> lists = threeSum(nums);
        System.out.println(ArrayUtil.toString(lists));

        quickSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    private static void quickSort(int[] nums, int leftIndex, int rightIndex) {
        if (leftIndex >= rightIndex) {
            return;
        }
        int left = leftIndex;
        int right = rightIndex;
        int pivot = nums[left];
        while (left < right) {

            while (left < right && nums[right] >= pivot) {
                right--;
            }
            nums[left] = nums[right];

            while (left < right && nums[left] <= pivot) {
                left++;
            }
            nums[right] = nums[left];

        }
        nums[left] = pivot;
        quickSort(nums, leftIndex, left - 1);
        quickSort(nums, right + 1, rightIndex);
    }

}
